<template>
  <view class="container">
	<cu-custom bgColor="bg-blue" :isBack="true" style="width: 100%;">
		<block slot="backText">返回</block>
		<block slot="content">考勤记录</block>
	</cu-custom>
    <!-- 头部月份导航 -->
    <view class="header">
      <view class="arrow-left" @click="changeMonth(-1)">◀</view>
      <text class="month-title">{{ currentMonth }}</text>
      <view class="arrow-right" @click="changeMonth(1)">▶</view>
    </view>

    <!-- 日历区域 -->
    <view class="calendar">
      <view class="weekdays">
        <text v-for="day in weekDays" :key="day" class="weekday">{{ day }}</text>
      </view>
      
      <view class="days">
        <view 
          v-for="(day, index) in daysData" 
          :key="index"
          :class="['day', { 
            'current-month': day.isCurrentMonth,
            'selected': day.date === selectedDate,
            'has-record': day.hasRecord 
          }]"
          @click="selectDate(day.date)"
        >
          <text class="day-number">{{ day.day }}</text>
          <view v-if="day.hasRecord" class="dot"></view>
        </view>
      </view>
    </view>

    <!-- 打卡记录列表 -->
    <scroll-view class="record-list" scroll-y>
      <view 
        v-for="(record, index) in records" 
        :key="index" 
        class="record-item"
      >
        <view class="time">
          <text class="type">{{ record.type }}</text>
          <text class="value">{{ record.time }}</text>
        </view>
        <view class="status">
          <text :class="['status-text', record.status]">{{ record.statusText }}</text>
        </view>
      </view>
      <view v-if="records.length === 0" class="no-data">暂无打卡记录</view>
    </scroll-view>
  </view>
</template>

<script>
import request from '@/common/request.js';
export default {
  data() {
    return {
        weekDays: ['日', '一', '二', '三', '四', '五', '六'],
        currentDate: new Date(),
        selectedDate: '',
		records: [],
		montuRecords:[],
		daysData:[]
    }
  },
  computed: {
    currentMonth() {
        return this.currentDate.toLocaleDateString('zh-CN', {
			year: 'numeric',
			month: 'long'
        })
    },
    filteredRecords() {
        return this.records.filter(r => r.date === this.selectedDate)
    }
  },
  mounted() {
	let that=this
    that.selectedDate = that.getTodayDate()
	
	const date=that.getCurrentDate();
	that.getAttendance(date)
	that.getMontuRecords(date)
  },
  methods: {
	    async getMontuRecords(date){
			let that=this
			let opts = {
				url: 'api/getAttendanceMonth',
				method: 'get'
			};
			let savingRequestData = {
				date: date,
			};
			that.montuRecords = [];
			request.httpTokenRequest(opts, savingRequestData).then(res => {
				if (res.data.code == 1) {
					this.$set(this, 'montuRecords', res.data.data.map(item => ({
						date: item.AddTime.split(' ')[0],
						// ...其他字段...
					})));
					// 清空原有数据
					if (res.data.data.length > 0) {
						// 格式化接口数据
						res.data.data.forEach(item => {
						// 转换时间格式（23:20:38 -> 23:20）
							const time = item.AddTime.split(' ')[1].substr(0, 5);
							// 构建打卡记录对象
							const record = {
								type: item.QrcodeName,     // 设备名称
								time: time,                // 打卡时间
								userId: item.SignUserId,   // 用户ID
								status: 'normal', // 状态判断
								statusText: '正常'
							};
							that.montuRecords.push(record);
						});
					}
					that.days()
				}
			})
	    },
		days() {
		    const date = new Date(this.currentDate)
		    const year = date.getFullYear()
		    const month = date.getMonth()
		  
		    // 生成当月天数
		    const daysInMonth = new Date(year, month + 1, 0).getDate()
		  
		    // 生成日历数据
		    const days = []
		  
		    // 添加上个月末尾几天
		    const firstDay = new Date(year, month, 1).getDay()
		    for (let i = 0; i < firstDay; i++) {
				days.push({
					day: '',
					date: '',
					isCurrentMonth: false,
					hasRecord: false
				})
		    }
		    //添加当月日期
		    for (let i = 1; i <= daysInMonth; i++) {
		        const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(i).padStart(2, '0')}`
		        days.push({
					day: i,
					date: dateStr,
					isCurrentMonth: true,
					hasRecord: this.montuRecords.some(r => r.date === dateStr)
		        })
		    }
			this.daysData=days
		},
	  getAttendance(date){
		let that=this
		let opts = {
			url: 'api/getAttendance',
			method: 'get'
		};
		let savingRequestData = {
		  date: date,
		};
		that.records = [];
		
		request.httpTokenRequest(opts, savingRequestData).then(res => {
			if (res.data.code == 1) {
					// 清空原有数据
					if (res.data.data.length > 0) {
					// 格式化接口数据
					res.data.data.forEach(item => {
					// 转换时间格式（23:20:38 -> 23:20）
					const time = item.AddTime.split(' ')[1].substr(0, 5);
					// 构建打卡记录对象
					const record = {
						type: item.QrcodeName,     // 设备名称
						time: time,                // 打卡时间
						userId: item.SignUserId,   // 用户ID
						status: 'normal', // 状态判断
						statusText: '正常'
					};

					that.records.push(record);

					});
					// 按时间排序（如果需要）
					that.records.sort((a, b) => a.time.localeCompare(b.time));
				}else {
					// uni.showToast({
					// 	title: '当日暂无打卡记录',
					// 	icon: 'none',
					// 	duration: 2000
					// });
				}
				// 更新页面数据
				that.$forceUpdate();
			} else {
				uni.showToast({
				title: res.data.msg || '数据加载失败',
				icon: 'none',
				duration: 3000
				});
			}
		})
	},
	getCurrentDate() {
		const date = new Date();
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
		const day = String(date.getDate()).padStart(2, '0');        // 日期补零
		return `${year}-${month}-${day}`;
	},
    getTodayDate() {
      const d = new Date()
      return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
    },
    changeMonth(offset) {
		const newDate = new Date(this.currentDate)
		newDate.setMonth(newDate.getMonth() + offset)
		this.currentDate = newDate
		this.records=[]
		console.log('newDate:'+newDate)
		const year = newDate.getFullYear();
		const month = String(newDate.getMonth() + 1).padStart(2, '0'); // 月份补零
		const day = String(newDate.getDate()).padStart(2, '0');        // 日期补零
		let date= `${year}-${month}-${day}`
		this.getMontuRecords(date)
    },
    selectDate(date) {
      if (date) this.selectedDate = date
	  this.getAttendance(date)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  
  .month-title {
    font-size: 36rpx;
    margin: 0 40rpx;
    color: #333;
  }
  
  .arrow-left, .arrow-right {
    font-size: 32rpx;
    color: #666;
    padding: 10rpx 20rpx;
  }
}

.calendar {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;

  .weekdays {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20rpx;
    
    .weekday {
      color: #666;
      font-size: 28rpx;
      width: 70rpx;
      text-align: center;
    }
  }

  .days {
    display: flex;
    flex-wrap: wrap;

    .day {
      width: 14.28%;
      height: 100rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      position: relative;
      
      &.current-month {
        .day-number {
          color: #333;
        }
      }
      
      &:not(.current-month) {
        .day-number {
          color: #ccc;
        }
      }
      
      &.selected {
        background: #0066FF;
        border-radius: 50%;
        
        .day-number {
          color: #fff !important;
        }
        
        .dot {
          background: #fff;
        }
      }
      
      .day-number {
        font-size: 32rpx;
      }
      
      .dot {
        width: 12rpx;
        height: 12rpx;
        background: #0066FF;
        border-radius: 50%;
        position: absolute;
        bottom: 10rpx;
      }
    }
  }
}

.record-list {
  height: 600rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;

  .record-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;
    
    .time {
      .type {
        color: #666;
        margin-right: 20rpx;
      }
      .value {
        color: #333;
        font-weight: bold;
      }
    }
    
    .status-text {
      padding: 8rpx 20rpx;
      border-radius: 40rpx;
      font-size: 24rpx;
      
      &.normal {
        background: #e8f5e9;
        color: #4CAF50;
      }
      
      &.late {
        background: #ffebee;
        color: #f44336;
      }
    }
  }

  .no-data {
    text-align: center;
    color: #999;
    padding: 40rpx;
  }
}
</style>